import {SERVICE_CONTEXT_PATH,CHECK_TOKEN_PATH} from '../Constants';
//配置请求组件
let KEY_USER = `user`;
let KEY_ACCESSTOKEN = `accessToken`;
let KEY_RETURNTO = `{returnTo}`;
export let ssoFilter = (router, axios, store)=> {
    router.beforeEach((to, from, next) => {
        //console.log("store token:" + store.state.sso.token);
        //console.log(store.state.user);
        //console.log("session token:" + sessionStorage.getItem("accessToken"));
        //console.log(sessionStorage.getItem("user"));
        if (store.state.sso.token && store.state.sso.token != `` && store.state.user.loginId) {
            next();
            //console.log("has token next");
        } else {
            let sessionUser = sessionStorage.getItem(KEY_USER);
            let sessionToken = sessionStorage.getItem(KEY_ACCESSTOKEN);
            if (sessionUser && sessionToken) {
                store.state.sso.token = sessionToken;
                store.state.user = sessionUser;
                next();
            } else {
                checkToken(axios, store).then(()=> {
                    next();
                    //console.log("without token next");
                });
            }
        }
    });
    axios.interceptors.request.use(
        config => {
            config.headers.common['X-Requested-With'] = `XMLHttpRequest`;
            console.log("axios token->" + store.state.sso.token)
            if (store.state.sso.token) {
                config.headers.common[`Authorization`] = `Bearer ${store.state.sso.token}`;
            }
            return config;
        },
        err => {
            return Promise.reject(err);
        }
    );
    axios.interceptors.response.use(
        response => {
            return response;
        },
        error => {
            if (error.response) {
                switch (error.response.status) {
                    case 401:
                        checkToken(axios, store);
                        break;
                    default:
                }
            }
            return Promise.reject(error);
        }
    );
};

let checkToken = (axios, store)=> {
    return new Promise((resolve, reject)=> {
        axios.get(CHECK_TOKEN_PATH, {
            baseURL: SERVICE_CONTEXT_PATH,
            params: {
                serviceTicket: getQueryStr("ticket")
            }
        }).then(response=> {
            if (response.status != 200) {
                //重定向到500页面
                reject(error);
            }
            if (response.status == 200) {
                if (response.data.code == 0) {
                    let repData = response.data.repData.replace(KEY_RETURNTO, encodeURIComponent(window.location.href));
                    window.location.href = repData;
                } else if (response.data.code == 1) {
                    store.state.user = response.data.repData.user;
                    store.state.sso.token = response.data.repData.accessToken;
                    sessionStorage.setItem(KEY_USER, response.data.repData.user);
                    sessionStorage.setItem(KEY_ACCESSTOKEN, response.data.repData.accessToken);
                    resolve(true);
                }
            }
        }).catch(error=> {
            //重定向到500页面
            reject(error);
        });
    });
};

let getQueryStr = (key)=> {
    let reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return r[2];
    }
    return null;
}
